package com.top10.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.top10.bean.ResponseBean;
import com.top10.bean.wxpay.PayRequest;
import com.top10.bean.wxpay.RefundRequest;
import com.top10.common.AliPayConst;
import com.top10.common.OrderConst;
import com.top10.common.WXPayConst;
import com.top10.entity.*;
import com.top10.entity.vo.UserCartGoodsVo;
import com.top10.enums.PayTypeEnum;
import com.top10.service.*;
import com.top10.utils.RandomUtils;
import com.top10.utils.WXUtil;
import com.top10.utils.WxPayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 微信支付Controller
 *
 * @author ellen
 * @version 1.0
 * @date 2018/10/14
 */
@RestController
@RequestMapping("/wx/manager")
public class WxPayController {
    private static final Logger logger = LoggerFactory.getLogger("system");

    @Autowired
    IOrderService orderService;
    @Autowired
    IUserDepositService userDepositService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    IUserCartService userCartService;
    @Autowired
    private IOrderDetailedService iOrderDetailedService;
    @Autowired
    private IGoodsDetailedService iGoodsDetailedService;

    /**
     * 微信支付异步通知
     *
     * @param request
     * @param response
     */
    @PostMapping("/asynNotify")
    public void asynNotify(HttpServletRequest request, HttpServletResponse response) {
        //异步通知
        Map<String, String> returnMap = WxPayUtil.asynNotify(request, response);
        if (returnMap == null) {
            return;
        }

        String outTradeNo = returnMap.get("out_trade_no"); //订单号
        String transactionId = returnMap.get("transaction_id"); //微信订单号

        //更新订单
        List<Order> orders = orderService.selectList(new EntityWrapper<Order>().eq("payid", outTradeNo));
        if (orders.size() !=0) {
            for (Order order : orders) {
                //设置该订单支付类型为：微信支付
                order.setPaytype(WXPayConst.PAY_TYPE);
                //修改该订单状态为 ：待发货
                order.setStatus(OrderConst.orderstatus1);
                //旧的状态为待支付
                order.setOldStatus(7);
                order.setUpdatetime(new Date());
                orderService.updateById(order);
                //处理购物清理的问题
                UserCartGoodsVo goods=iOrderDetailedService.selectGoods(order.getId());
                if(goods!=null){
                    if(goods.getAttributes().equals("{}") || goods.getAttributes()==null){
                        userCartService.delete(new EntityWrapper<UserCart>().eq("user_uuid",order.getUserUuid()).eq("goods_uuid",goods.getGoods_uuid()).eq("isdeleted",false));
                    }else{
                        userCartService.delete(new EntityWrapper<UserCart>().eq("user_uuid",order.getUserUuid()).eq("goods_uuid",goods.getGoods_uuid()).eq("attributes",goods.getAttributes()).eq("ideleted",false));
                    }

                }
                //销量增加
                List<OrderDetailed> orderDetailedsLists=iOrderDetailedService.selectList(new EntityWrapper<OrderDetailed>().eq("order_uuid",order.getUuid()));
                for(OrderDetailed orderDetailedList:orderDetailedsLists) {
                    GoodsDetailed goodsDetailed = iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("uuid", orderDetailedList.getGoodsDetailedUuid()));
                    goodsDetailed.setSoldQuantity(goodsDetailed.getSoldQuantity()+orderDetailedList.getQuantity());
                    iGoodsDetailedService.updateById(goodsDetailed);
                }

            }
        }
        UserDeposit userDeposit=userDepositService.selectOne(new EntityWrapper<UserDeposit>().eq("order_sn",outTradeNo));
        User user=iUserService.selectOne(new EntityWrapper<User>().eq("uuid",userDeposit.getUid()));
        user.setMoney(user.getMoney().add(userDeposit.getMoney()));
        userDeposit.setOrderStatus(1);
        userDeposit.setTradeTime(new Date());
        userDepositService.updateById(userDeposit);
        iUserService.updateById(user);


    }

    /**
     * 微信支付
     *
     * @param payid
     * @param type  0订单 1充值
     * @return
     */
    @RequestMapping("/pay")
    public ResponseBean pay(String payid, Long type) throws Exception {
        if (type == null || "".equals(type)) {
            return ResponseBean.createError("支付类型不能为空");
        }

        double actualPrice = 0;
        if (type == 1) {
            if (payid == null || "".equals(payid)) {
                return ResponseBean.createError("订单号不能为空");
            }

            List<Order> orders = orderService.selectList(new EntityWrapper<Order>().eq("payid", payid));
            if (orders == null) {
                return ResponseBean.createError("不存在该订单，支付发生错误");
            }

            for (Order order : orders) {
                actualPrice += order.getActualPrice();
            }


        }

        if (type == 2) {

            if (payid == null || "".equals(payid)) {
                return ResponseBean.createError("充值订单号不能为空");
            }

            UserDeposit userDeposit = userDepositService.selectOne(new EntityWrapper<UserDeposit>().eq("order_sn", payid));
            if (userDeposit == null) {
                return ResponseBean.createError("不存在该信息，充值发生错误");
            }
            actualPrice = userDeposit.getMoney().doubleValue();
        }

        PayRequest payRequest = new PayRequest();
        payRequest.setOutTradeNo(payid);
        payRequest.setOrderAmount((int) (actualPrice * 100));
        payRequest.setOrderName("顶十商城");
        payRequest.setPayTypeEnum(PayTypeEnum.WXPAY_APP); //交易类型
        payRequest.setNotifyUrl(WXPayConst.ORDER_NOTIFYURL); //异步通知地址
        Map<String, String> resultMap = WxPayUtil.pay(payRequest, "");

        return ResponseBean.createSuccess().addData("resultMap", resultMap);
    }

    /**
     * 微信退款
     *
     * @param orderId
     * @param refundFee
     * @return
     * @throws Exception
     */
    @RequestMapping("/refund")
    public ResponseBean refund(String orderId, Integer refundFee) throws Exception {
        if (orderId == null || orderId.trim().equals("")) {
            return ResponseBean.createError("订单流水id不能为空");
        }
        if (refundFee == null) {
            return ResponseBean.createError("退款金额不能为空");
        }

        Order order = orderService.selectOne(new EntityWrapper<Order>().eq("orderid", orderId));
        if (order == null) {
            return ResponseBean.createError("找不到该订单");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String outRefundNo = sdf.format(new Date()) + RandomUtils.makeRandomDigit6() + RandomUtils.getNBitRandomDigit(4);

        RefundRequest refundRequest = new RefundRequest();
        refundRequest.setOutRefundNo(outRefundNo);
        refundRequest.setOutTradeNo(orderId);
        refundRequest.setOrderAmount((int) (order.getActualPrice() * 100));
        refundRequest.setRefundFee(refundFee);

        Map<String, String> resultMap = WxPayUtil.refund(refundRequest, WXPayConst.CERTIFICATE_PATH, WXPayConst.PAYAPISECRET, WXPayConst.MCHKEY);

        order.setBatchNo(outRefundNo); //退款单号
        order.setStatus(OrderConst.orderstatus6); //状态 同意退款

        return ResponseBean.createSuccess().addData("resultMap", resultMap);
    }

    /**
     * 测试微信支付
     *
     * @param payRequest
     * @return
     */
    @PostMapping("/wxPay")
    public ResponseBean wxPay(@Valid PayRequest payRequest, Errors errors) throws Exception {
        if (errors.hasErrors()) {
            return ResponseBean.createError(errors.getFieldError().getDefaultMessage());
        }

        payRequest.setPayTypeEnum(PayTypeEnum.WXPAY_APP); //交易类型
        payRequest.setNotifyUrl(WXPayConst.ORDER_NOTIFYURL); //异步通知地址
        Map<String, String> resultMap = WxPayUtil.pay(payRequest, "");

        return ResponseBean.createSuccess().addData("resultMap", resultMap);
    }

    /**
     * 测试微信退款
     *
     * @param refundRequest
     * @param errors
     * @return
     * @throws Exception
     */
    @PostMapping("/wxRefund")
    public ResponseBean wxRefund(@Valid RefundRequest refundRequest, Errors errors) throws Exception {
        if (errors.hasErrors()) {
            return ResponseBean.createError(errors.getFieldError().getDefaultMessage());
        }

        Map<String, String> resultMap = WxPayUtil.refund(refundRequest, WXPayConst.CERTIFICATE_PATH, WXPayConst.PAYAPISECRET, WXPayConst.MCHKEY);

        return ResponseBean.createSuccess().addData("resultMap", resultMap);
    }

}